package com.reactsdk.sid

import com.facebook.react.bridge.Callback
import com.facebook.react.bridge.ReadableMap

object SIDUtils {

	const val INVALID_PARAMS = "INVALID_PARAMS "
	inline fun <reified T> ReadableMap.getParamOrNull(param: String, promise: Callback): T? {
		return runCatching {
			when (T::class) {
				String::class -> getString(param)
				Int::class -> getInt(param)
				Double::class -> getDouble(param)
				Boolean::class -> getBoolean(param)
				else -> null
			}
		}.getOrElse {
			sendMessageToPromise(msg = param, promise = promise)
			return null
		} as? T
	}

	inline fun <reified T> ReadableMap.getParamOrException(param: String, promise: Callback): T {
		return runCatching {
			when (T::class) {
				String::class -> getString(param)
				Int::class -> getInt(param)
				Double::class -> getDouble(param)
				Boolean::class -> getBoolean(param)
				else -> null
			}
		}.getOrElse {
			sendMessageToPromise(msg = param, promise = promise)
			error(INVALID_PARAMS)
		} as T
	}

	fun sendMessageToPromise(msg: String, promise: Callback) {
		promise(INVALID_PARAMS, msg)
	}
}

